<template>
  <div>
    <el-card>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="dialogVisible = true">添加</el-button>
      <!-- 表格 -->
      <el-table
        :border="true"
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        style="width: 100%"
        height="75vh"
      >
        <el-table-column type="index" width="80" align="center" label="序号">
        </el-table-column>
        <el-table-column property="tmName" label="品牌名称" width="width">
        </el-table-column>
        <el-table-column label="品牌logo" width="width">
          <!-- 作用域插槽 -->
          <template slot-scope="{ row, column, $index }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 200px; height: 100px; object-fit: contain"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="width">
          <template slot-scope="{ row, column, $index }">
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="editTradeMark(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delTradeMark(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div style="text-align: center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 对话框,表单 -->
    <el-dialog
      :title="trademarkId ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 表单 -->
      <el-form
        label-position="left"
        label-width="80px"
        :rules="rules"
        :model="form"
        ref="myForm"
      >
        <el-form-item label="品牌名称" prop="trademarkName">
          <el-input v-model="form.trademarkName"></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" prop="imageUrl">
          <!-- 图片上传 -->
          <el-upload
            class="avatar-uploader"
            action="dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- <button> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="AddOrEditTradeMark">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tradeMarkInfo: {},
      // 分页器
      currentPage: 1,
      limit: 5,
      // 对话框,表单
      dialogVisible: false,
      form: {
        trademarkName: '',
        imageUrl: ''
      },
      trademarkId: '',

      rules: {
        trademarkName: [
          { required: true, message: '请输入品牌名称', trigger: 'change' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'change'
          }
        ],
        //品牌的logo验证规则
        imageUrl: [{ required: true, message: '请选择品牌的图片' }]
      }
    }
  },
  computed: {
    // 表格数据
    tableData() {
      return this.tradeMarkInfo.records || []
    },
    total() {
      return this.tradeMarkInfo.total || 0
    }
  },
  methods: {
    // 获取品牌列表信息
    async getTradeMarkList() {
      const res = await this.$API.trademark.reqGetTradeMarkList(
        this.currentPage,
        this.limit
      )
      if (res.code == 200) {
        this.tradeMarkInfo = res.data
      }
    },
    // 当前页改变
    handleCurrentChange(num) {
      this.currentPage = num

      this.getTradeMarkList()
    },
    // 每一页要展示的数据量改变
    handleSizeChange(val) {
      this.limit = val
      this.getTradeMarkList()
    },
    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
      // 清除表单信息
      this.form.trademarkName = ''
      this.form.imageUrl = ''
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      // 保存返回的URL,不是本地URL,要带给服务器的
      // this.form.imageUrl = URL.createObjectURL(file.raw)
      this.form.imageUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传或修改品牌信息
    AddOrEditTradeMark() {
      // 表单验证
      this.$refs['myForm'].validate(async (valid) => {
        if (valid) {
          // 有id就修改,没有ID就是上传
          const data = {
            id: this.trademarkId ? this.trademarkId * 1 : undefined,
            logoUrl: this.form.imageUrl,
            tmName: this.form.trademarkName
          }
          const res = await this.$API.trademark.reqAddOrEditTradeMark(data)
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: this.trademarkId ? '修改品牌成功' : '添加品牌成功'
            })
            // 跟新列表数据
            this.getTradeMarkList()
          } else {
            this.$message({ type: 'error', message: res.data || res.message })
          }
          // 清除表单信息
          this.form.trademarkName = ''
          this.form.imageUrl = ''
          this.trademarkId = ''

          // 关闭对话框
          this.dialogVisible = false
        } else {
          this.$message({ type: 'warning', message: '信息不完整' })
          return false
        }
      })
    },
    // 点击修改品牌
    editTradeMark(data) {
      // 将信息显示到表单上
      this.trademarkId = data.id
      this.form.trademarkName = data.tmName
      this.form.imageUrl = data.logoUrl
      this.dialogVisible = true
    },
    // 删除品牌
    async delTradeMark(id) {
      try {
        await this.$confirm('此操作将永久删除该品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 没有异常就是确定
        let res = await this.$API.trademark.reqDelTradeMark(id)
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 从新获取列表
          this.getTradeMarkList()
        } else {
          this.$message({
            type: 'error',
            message: res.data || res.message
          })
        }
      } catch (err) {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
    }
  },
  created() {
    this.getTradeMarkList()
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
